package com.jia.netty.handler;

import com.google.gson.Gson;
import com.jia.entity.netty.CoonMsg;
import com.jia.entity.netty.ShutDownMsg;
import com.jia.netty.channel.ChannelGroup;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.data.redis.core.StringRedisTemplate;

public class CoonHandler extends SimpleChannelInboundHandler<CoonMsg> {


    private StringRedisTemplate redisTemplate;

    public CoonHandler(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, CoonMsg coonMsg) throws Exception {
        System.out.println("新的连接：" + coonMsg);
        ChannelGroup.addChannel(coonMsg.getDid(),channelHandlerContext.channel());
        // 根据用户id在redis中查设备id
        String uid = coonMsg.getUid();
        String did = coonMsg.getDid();

        String redisDid = redisTemplate.opsForValue().get(uid);
        if(redisDid != null && !redisDid.equals(did)){
            TextWebSocketFrame resp = new TextWebSocketFrame(new Gson().toJson(new ShutDownMsg()));
            channelHandlerContext.writeAndFlush(resp);
        }
    }


}
